import * as types from '../mutation-types'

import moment from 'moment'
import { localUser } from '@/assets/js/local'
import { JIMConf } from '@/api/config'
import { randomWord } from '@/assets/js/utils'
import md5 from 'js-md5'
import defaultAvatar from '@/assets/img/default_avatar.png'

const state = {
  JIM: null,
  chatObject: {},
  chatMsgList: [],
  receiveMsg: [],
  syncConversation: [],
  unreadChatCount: 0,
  AIMsgList: []
}

const getters = {
  JIM: state => state.JIM,
  chatObject: state => state.chatObject,
  chatMsgList: state => state.chatMsgList,
  receiveMsg: state => state.receiveMsg,
  syncConversation: state => state.syncConversation,
  unreadChatCount: state => state.unreadChatCount,
  AIMsgList: state => state.AIMsgList
}

const mutations = {
  [types.SET_JIM] (state, JIM) {
    state.JIM = JIM
  },
  [types.SET_CHAT_OBJECT] (state, chatObject) {
    state.chatObject = chatObject
  },
  [types.SET_CHAT_MSG_LIST](state, msgList) {
    state.chatMsgList = msgList
  },
  [types.PUSH_CHAT_MSG_LIST](state, msg) {
    state.chatMsgList.push(msg)
  },
  [types.SET_RECEIVE_MSG](state, receiveMsg) {
    state.receiveMsg = receiveMsg
  },
  [types.SET_SYNC_CONVERSATION](state, syncConversation) {
    state.syncConversation = syncConversation
  },
  [types.PUSH_SYNC_CONVERSATION](state, msg) {
    state.syncConversation.forEach(item => {
      if (item.from_username === msg.username) {
        item.msgs.push({
          content: {
            create_time: msg.sendTime,
            from_id: msg.id,
            msg_body: {
              text: msg.content
            }
          },
          ctime_ms: msg.sendTime
        })
      }
    })
  },
  [types.SET_UNREAD_CHAT_COUNT](state, count) {
    state.unreadChatCount = count
  },
  [types.PUSH_AI_MSG_LIST](state, msg) {
    state.AIMsgList.push(msg)
  },
  [types.SET_AI_MSG_LIST](state, msg) {
    state.AIMsgList = msg
  }
}

const actions = {
  initJIM({ commit, state }) {
    // 注册全局JMessage对象
    let params = {
      appkey: JIMConf.key,
      random_str: randomWord(1, 20, 32),
      timestamp: new Date().getTime(),
      flag: 1
    }
    params.signature = md5(`appkey=${params.appkey}&timestamp=${params.timestamp}&random_str=${params.random_str}&key=${JIMConf.secret}`)
    const JIM = new JMessage()
    const user = localUser.get()
    JIM.init(params).onSuccess((data) => {
      if (user && !JIM.isLogin()) {
        JIM.login({
          username: user.id,
          password: user.password,
          is_md5: true
        }).onSuccess(function () {
          localUser.setItem('id', user.id)
          commit(types.SET_JIM, JIM)
        }).onFail((e) => {
          if (e.code === 880103) {
            JIM.register({
              username: user.id,
              password: user.password,
              is_md5: true,
              nickname: user.nickname
            }).onSuccess(() => {
              // 注册成功过后重新登录
              JIM.login({
                username: user.id,
                password: user.password,
                is_md5: true
              }).onSuccess(function () {
                localUser.setItem('id', user.id)
              })
            })
          }
        })
      } else {
        commit(types.SET_JIM, JIM)
      }
      JIM.onMsgReceive(function (rmsg) {
        commit(types.SET_RECEIVE_MSG, rmsg)
        let tmp = []
        rmsg.messages.forEach(item => {
          tmp.push({
            id: item.msg_id,
            type: 'from',
            nickname: state.chatObject.nickname,
            headUrl: state.chatObject.headUrl || defaultAvatar,
            content: item.content.msg_body.text,
            contentType: 0,
            sendTime: item.content.create_time
          })
          if (item.from_username !== state.chatObject.id) {
            commit(types.SET_UNREAD_CHAT_COUNT, state.unreadChatCount + rmsg.messages.length)
          }
        })
        commit(types.SET_CHAT_MSG_LIST, state.chatMsgList.concat(tmp))
      })
      JIM.onSyncConversation(function (scon) {
        // 获取离线数据的时候还没有设置聊天对象
        commit(types.SET_SYNC_CONVERSATION, scon)
        // 设置未读数
        let count = 0
        scon.forEach(item => {
          count += item.unread_msg_count
        })
        commit(types.SET_UNREAD_CHAT_COUNT, count)
      })
    })
  },
  setChatObject({ commit, dispatch, state }, chatObj) {
    if (state.JIM == null || !state.JIM.isInit() || !state.JIM.isLogin()) {
      dispatch('initJIM')
      return
    }
    // 1、设置聊天对象
    commit(types.SET_CHAT_OBJECT, chatObj)
    // 2、获取离线记录
    const user = localUser.get()
    let tmp = []
    state.syncConversation.forEach(item => {
      if (item.from_username === chatObj.id && item.msgs) {
        item.msgs.forEach((msg, index) => {
          tmp.push({
            id: msg.msg_id,
            type: (typeof msg.content.from_id === 'number') || msg.content.from_id === user.id ? 'to' : 'from',
            nickname: msg.content.from_name,
            headUrl: msg.content.from_id === user.id ? user.headUrl : chatObj.headUrl,
            content: msg.content.msg_body.text,
            contentType: 0,
            sendTime: msg.content.create_time
          })
        })
      }
    })
    tmp.forEach((item, index) => {
      if (moment().diff(moment(item.sendTime), 'days') <= 1) {
        item.sendTimeStr = moment(item.sendTime).format('HH:mm')
      } else {
        item.sendTimeStr = moment(item.sendTime).format('YYYY-MM-DD HH:mm')
      }
      if (item.headUrl == null) {
        item.headUrl = defaultAvatar
      }
      if (index > 0) {
        if (moment(item.sendTime).diff(moment(tmp[index - 1].sendTime), 'minutes') < 4) {
          item.sendTimeStr = ''
        }
      }
    })
    commit(types.SET_CHAT_MSG_LIST, tmp)
    // 重置会话未读数
    const tmpCount = state.JIM.getUnreadMsgCnt({
      username: chatObj.id
    })
    commit(types.SET_UNREAD_CHAT_COUNT, state.unreadChatCount - tmpCount)
    state.JIM.resetUnreadCount({
      username: chatObj.id
    })
  },
  sendMsg({ commit, state }, msg) {
    commit(types.PUSH_CHAT_MSG_LIST, msg)
    commit(types.PUSH_SYNC_CONVERSATION, msg)
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
